<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <button>按钮</button><button>按钮</button><button>按钮</button
      ><button>按钮</button><button>按钮</button><button>按钮</button
      ><button>按钮</button><button>按钮</button><button>按钮</button
      ><button>按钮</button>
    </div>

    <script>
      const containerEl = document.querySelector(".container");

      // 事件委托
      /* containerEl.addEventListener("click", function (e) {
        if (e.target.tagName === "BUTTON") {
          const btns = Array.prototype.slice.call(containerEl.children);
          const index = btns.indexOf(e.target);
          console.log(index);
        }
      }); */

      // let，函数作用域
      const btns = document.querySelectorAll("button");
      for (let i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function () {
          console.log(i);
        });
      }
    </script>
  </body>
</html>
